layui.use(['form', 'layer', 'config', 'admin', 'xmSelect', 'jquery'], function () {
    let form = layui.form,
        layer = layui.layer,
        config = layui.config,
        $ = layui.jquery,
        admin = layui.admin,
        xmSelect = layui.xmSelect;
    let userid = config.getUser().id;

    // 解决使用菜单项页面作为弹窗时，页面存在多个相同元素节点，导致需id（唯一）渲染的节点渲染失败
    let randomNum = Math.uuid(8);
    let renderNodeIds = [];
    let renderNodes = $('#adminPopupC').length > 0 ? $('#adminPopupC .random-node') : $('.random-node');
    for (let node of renderNodes) {
        let classSplit = $(node).attr('class').split(" ")[1];
        let randId = classSplit.concat(randomNum);
        renderNodeIds.push('#'.concat(randId));
        $(node).attr('id', randId);
    }

    let articleCache = admin.getTempData('t_article'); // 缓存的文章数据
    let articleId = $("#adminPopupC input[name='arleid']").val(); // 文章id

    // 文章标签下拉框渲染
    let tagsStore = {};
    renderXmSelect({
        el: renderNodeIds[0],
        tips: '请选择文章标签',
        name: 'artags',
        initValue: processInitValue('artags', articleCache),
        prop: {name: 'taname', value: 'taname', theme: {color: '#8dc63f', maxColor: 'orange'}}
    }, 'api-forum/article/tags/'.concat(userid), tagsStore);

    // 文章分类专栏下拉框渲染
    let categoryStore = {};
    renderXmSelect({
        el: renderNodeIds[1],
        tips: '请选择分类专栏',
        name: 'catgry',
        initValue: processInitValue('catgry', articleCache),
        prop: {name: 'caname', value: 'caname', id: 'cateid'},
        theme: {color: '#fbbd08 ', maxColor: 'orange'}
    }, 'api-forum/article/category/'.concat(userid), categoryStore);

    // 处理下拉列表初始化选中值
    function processInitValue(field, data) {
        return data && data[field] ? data[field].split(",") : [];
    }

    // 渲染xm-select下拉框
    function renderXmSelect(options, url, store) {
        let origin = [];
        store.append = [];  // 从选中的标签项中追加已拥有（创建）的
        store.created = []; // 新创建的标签项
        store.removed = []; // 从选中标签项中移除的标签
        store.prop = options.prop;
        let select = xmSelect.render({
            el: options.el,
            tips: options.tips ? options.tips : '请选择',
            searchTips: options.searchTips ? options.searchTips : '请选择或创建标签',
            name: options.name,
            prop: options.prop,
            initValue: options.initValue ? options.initValue : '',
            data: [],
            paging: true,
            pageSize: 5,
            filterable: true,
            max: 5,
            theme: options.theme ? options.theme : {color: '#8dc63f', maxColor: 'red'},
            create: function (val, arr) {
                if (arr.length === 0) {
                    //返回一个创建成功的对象, val是搜索的数据, arr是搜索后的当前页面数据
                    let obj = {};
                    obj[options.prop.name] = val;
                    obj[options.prop.value] = val;
                    return obj;
                }
            },
            on: (e) => {
                let key = e.change[0][options.prop.name],
                    value = e.change[0][options.prop.id];
                let isKeyExist = origin.indexOf(key) > -1,
                    isKeyExistOwn = options.initValue ? options.initValue.indexOf(key) > -1 : false;
                let createdIndex = store.created.indexOf(key), appendIndex = store.append.indexOf(value),
                    removedIndex = store.removed.indexOf(value);
                let keyExistCreated = {index: createdIndex, isExist: createdIndex > -1},
                    keyExistAppend = {index: appendIndex, isExist: appendIndex > -1},
                    keyExistRemoved = {index: removedIndex, isKeyExist: removedIndex > -1};
                e.isAdd && !isKeyExist && !keyExistCreated.isExist ? store.created.push(key) :                            // 当动作为添加、并且未创建此添加项、且新建项并未存储 - 存储此创建项
                    (e.isAdd && !isKeyExistOwn && !keyExistAppend.isExist ? store.append.push(value) :                    // 当动作为添加、并且未拥有此添加项、且追加项并未存储 - 存储此追加项
                        (e.isAdd && keyExistRemoved.isKeyExist ? store.removed.splice(keyExistRemoved.index, 1) :         // 当动作为添加、并且此移除项已存储                   - 删除此移除项
                            (!e.isAdd && keyExistCreated.isExist ? store.created.splice(keyExistCreated.index, 1) :       // 当动作为移除、并且此创建项已存储                   - 删除此创建项
                                (!e.isAdd && keyExistAppend.isExist) ? store.append.splice(keyExistAppend.index, 1) :     // 当动作为移除、并且此追加项已存储                   - 删除此追加项
                                    (!e.isAdd && isKeyExistOwn && !keyExistRemoved.isKeyExist) ? store.removed.push(value) : // 当动作为移除、并且已拥有此移除项、且移除项并未存储 - 存储此移除项
                                        console.log('throw xm-select listening change'))));
            }
        });
        admin.req(url, {}, (res) => {
            for (let item of res) origin.push(item[select.options.prop.name]); // 填充源标签
            select.update({data: res, autoRow: true}) // 标签控件填充数据
        }, 'GET');
        return select;
    }

    // 填充下拉列表 - 文章类型
    let articleTypeSelect = admin.getTempData('articleTypeSelect');
    if (articleTypeSelect && articleTypeSelect.length > 0) {
        $.each(articleTypeSelect, function (index, item) {
            let option = new Option(item.mtname, item.mtcode);
            $(".articleForm select[name='artype']").append(option);
        });
        form.render();
    } else {
        admin.req('api-forum/article/articleType', {}, (data) => {
            $.each(data, function (index, item) {
                let option = new Option(item.mtname, item.mtcode);
                $(".articleForm select[name='artype']").append(option);
            });
            form.render();
        }, 'GET');
    }

    // 开关样式渲染
    $('.toggle').toggles({
        on: true,
        text: {
            on: '开启',
            off: '关闭'
        }
    });

    // markdown编辑器初始化
    editormd(renderNodeIds[2].split("#")[1], {//注意1：这里的就是上面的DIV的id属性值
        width: "90%",
        height: 640,
        syncScrolling: "single",
        path: "../assets/libs/editormd/lib/",//注意2：你的路径
        saveHTMLToTextarea: true,//注意3：这个配置，方便post提交表单
        emoji: true,
        /**上传图片相关配置如下*/
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"], //图片上传格式
        imageUploadURL: "api-file/files-anon",
        onload: function (obj) { //上传成功之后的回调
        }
    });

    // 编辑文章下 - 表单控件赋值
    if (articleCache) {
        articleCache['my-text'] = articleCache.detail;
        delete articleCache.detail;
        form.val('articleForm', articleCache);
        let awcomt = $("input[name='awcomt']");
        awcomt.val() !== '1' ? awcomt.next().click() : 0;
    }


    // 提交文章
    form.on('submit(subArticel)', (data) => {
        let params = data.field;
        params.astate = data.elem.lang; // 设置文章状态
        params.userid = config.getUser().id;
        delete params['my-text'];
        // 如果存在新创建的分类专栏
        if (categoryStore.created.length > 0) {
            params.createdCategories = [];
            for (let category of categoryStore.created) params.createdCategories.push({
                userid: userid,
                caname: category
            });
        }
        // 如果存在新追加的分类专栏
        if (!articleId && categoryStore.append.length > 0) {
            params.appendCategories = [];
            for (let key of categoryStore.append) {
                let obj = {};
                obj[categoryStore.prop.id] = key;
                params.appendCategories.push(obj);
            }
        }
        layer.load(2);
        storeSubmit(tagsStore, {created: 'api-forum/article/tags/batchSave'});
        storeSubmit(categoryStore, {
            // created: 'api-forum/article/category/created/'.concat($("#adminPopupC input[name='arleid']").val()),
            append: 'api-forum/article/category/append',
            removed: 'api-forum/article/category/removed/'.concat(params.arleid)
        });
        admin.req('api-forum/article/saveOrUpdate', JSON.stringify(params), (data) => {
            layer.closeAll('loading');
            if (data.code === 0) {
                layer.msg(data.msg, {icon: 1, time: 500});
                if ($("#adminPopupC").length > 0) admin.finishPopupCenter();
            } else {
                layer.msg(data.msg, {icon: 2, time: 500});
            }
        }, 'POST');
    });

    // xm-select变动项存储提交
    function storeSubmit(store, urls) {
        if (store) {
            if (store.created.length > 0 && urls.created) {
                let params = [];
                for (let key of store.created) {
                    let obj = {};
                    obj[store.prop.name] = key;
                    obj.userid = userid;
                    params.push(obj);
                }
                admin.req(urls.created, JSON.stringify(params), (res) => {
                    console.log(res.msg)
                }, 'POST')
            } else if (store.append.length > 0 && urls.append && articleId) {
                let params = [];
                for (let key of store.append) {
                    let obj = {};
                    obj[store.prop.id] = key;
                    obj.arleid = articleId;
                    params.push(obj);
                }
                admin.req(urls.append, JSON.stringify(params), (res) => {
                    console.log(res.msg)
                }, 'POST')
            } else if (store.removed.length > 0 && urls.removed) {
                admin.req(urls.removed, {ids: store.removed}, (res) => {
                    console.log(res.msg)
                }, 'DELETE')
            }
        }
    }
})
;

// 允许评论
function allow_comment(e) {
    $("input[name='awcomt']")[0].value = $(e).find('.toggle-on').hasClass('active') ? 0 : 1;
}

function allow_ping() {

}

function allow_feed() {

}